package com.example.warehouse.service.serviceImpl;

import com.example.warehouse.dto.AssignAuthDto;
import com.example.warehouse.entity.AuthRode;
import com.example.warehouse.entity.Role;
import com.example.warehouse.mapper.RoleMapper;
import com.example.warehouse.page.Page1;
import com.example.warehouse.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@CacheConfig(cacheNames = "com.example.warehouse.service.serviceImpl.RoleServiceImpl")
public class RoleServiceImpl implements RoleService{
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    @Cacheable(key = "'role:all'")
    public List<Role> getAllRole() {
        return  roleMapper.findAllRole();
    }

    @Override
    public List<Role> QueryID(Integer userId) {
        return roleMapper.QueryByUid(userId);
    }

    @Override
    public Page1 QueryRolePage(Page1 page1, Role role) {
        Integer count = roleMapper.FindRoleRowCount(role);
        List<Role> pageRoleList = roleMapper.FindRoleList(page1, role);
        page1.setPageNum(count);
        page1.setResultList(pageRoleList);
        return page1;
    }

    @Override
    public boolean DeleteById(Integer roleId) {
        roleMapper.deleteById(roleId);
        return true;
    }

    @Override
    public boolean updateRoleState(Role role) {
        roleMapper.updateRoleState(role);
        return true;
    }

    @Override
    public boolean updateRoleById(Role role) {
        roleMapper.updataRoleById(role);
        return true;
    }

    @Override
    public void addRole(Role role) {
        roleMapper.addRole(role);
    }

    @Override
    public List<Integer> FindAuthByroleId(Integer roleId) {
        return roleMapper.FindRoleAuth(roleId);
    }

    @Override
    public boolean deleteAuthByRoleId(Integer roleId) {
        roleMapper.deleteAuthByRole(roleId);
        return true;
    }

    @Transactional
    @Override
    public void AddAuthByRoled(AssignAuthDto assignAuthDto) {
        List<Integer> authIds = assignAuthDto.getAuthIds();
        for(Integer authid:authIds) {
            AuthRode authRode=new AuthRode();
            authRode.setRoleId(assignAuthDto.getRoleId());
            authRode.setAuthId(authid);
            roleMapper.addAuthByRoleId(authRode);
        }
    }



}
